package top.yehot.cmmu.spring.handler;

import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import com.alibaba.fastjson2.JSON;

import top.yehot.cmmu.core.base.JResult;
import top.yehot.cmmu.spring.interceptor.ResponseResultInterceptor;

/**
 * 对controller返回值进行封装
 * 
 * @author lquan
 * @date 2022年4月2日 下午4:34:07
 */
@ControllerAdvice
public class ResponseResultHandler implements ResponseBodyAdvice<Object> {

	@Override
	public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
		ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		Object attriVal = (sra.getRequest()).getAttribute(ResponseResultInterceptor.RESPONSE_RESULT_ANN);
		return null == attriVal ? false : true;
	}

	@Override
	public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, 
			ServerHttpRequest request, ServerHttpResponse response) {
		if (body instanceof JResult) {
			return body;
		}
		if (body instanceof String) {
			return JSON.toJSONString(JResult.success(body));
		}
		return JResult.success(body);
	}

}
